import pandas as pd
import numpy as np
# 数据集文件夹名
DATADIR = 'D:/UCI HAR Dataset'
#各个传感器方向名
SIGNALS = [
    "body_acc_x","body_acc_y","body_acc_z","body_gyro_x","body_gyro_y","body_gyro_z","total_acc_x","total_acc_y","total_acc_z"
]
# 定义读取数据方法
def load_x(subset):
    signals_data = []
    for signal in SIGNALS:
        #数据集的文件夹位置
        filename = '{0}/{1}/Inertial Signals/{2}_{1}.txt'.format(DATADIR, subset, signal)
        signals_data.append(
            pd.read_csv(filename, delim_whitespace=True, header=None).values
        )
    return np.transpose(signals_data, (1, 2, 0))

# 定义读取标签方法
def load_y(subset):
    filename = '{0}/{1}/y_{1}.txt'.format(DATADIR,subset)
    y = pd.read_csv(filename, delim_whitespace=True, header=None)[0]
    return pd.get_dummies(y).values

# 定义加载数据
def load_data():
    x_train, x_test = load_x('train'), load_x('test')
    y_train, y_test = load_y('train'), load_y('test')
    return x_train, x_test, y_train, y_test

# 运行加载数据
X_train, X_test, Y_train, Y_test = load_data()

epochs = 30  # 训练次数
batch_size = 16  # 每个批次大小
n_hidden = 16#隐层单元个数
n_classes = 6#类别个数
timesteps = len(X_train[0])
input_dim = len(X_train[0][0])

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Dropout
model = Sequential()
model.add(LSTM(n_hidden, input_shape=(timesteps, input_dim)))
model.add(Dense(n_classes, activation='softmax'))
model.compile(loss='categorical_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy'])
model.fit(X_train,
          Y_train,
          batch_size=batch_size,
          validation_data=(X_test, Y_test),
          epochs=epochs)

scores = model.evaluate(X_test,Y_test)
print(scores[1])

predicts = model.predict(X_test)
ACTIVITIES = {0: '走', 1: '上楼', 2: '下楼', 3: '坐', 4: '站', 5: '躺'}

def confusion_matrix(Y_true, Y_pred):
    Y_true = pd.Series([ACTIVITIES[y] for y in np.argmax(Y_true, axis=1)])
    Y_pred = pd.Series([ACTIVITIES[y] for y in np.argmax(Y_pred, axis=1)])
    return pd.crosstab(Y_true, Y_pred, rownames=['True'], colnames=['Pred'])

print(confusion_matrix(Y_test,predicts))
